package main

import (
	"Go36/article48/common"
	"Go36/article48/common/op"
	"errors"
	"fmt"
	"io"
	"os"
	"runtime/pprof"
)

func main() {
	// 打开文件，准备写入
	filename := "cpuprofile.out"
	f, err := os.Create(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Create File Error: %v", err)
		return
	}
	defer f.Close()

	// 进行采样
	if err := startCPUProfile(f); err != nil {
		fmt.Fprintf(os.Stderr, "CPU profile start error: %v\n", err)
		return
	}
	// 被测试的函数
	if err := common.Execute(op.CPUProfile, 10); err != nil {
		fmt.Fprintf(os.Stderr, "execute error: %v\n", err)
		return
	}
	// 停止采样
	stopCPUProfile()
}

func startCPUProfile(w io.Writer) error {
	if w == nil {
		return errors.New("nil File")
	}
	return pprof.StartCPUProfile(w)
}

func stopCPUProfile() {
	pprof.StopCPUProfile()
}
